<?php
/*
 * 08/15
 * william for write
 * yangxinpeng (19.9)
 * */
namespace app\common\service\lib;

class Tuling
{
    protected $apiKey;
    protected $url;

    public function __construct()
    {
        $this->apiKey = config('setting.tuling.apiKey');
        $this->url = config('setting.tuling.url');
    }
    /**
     * Author:William
     * @param string $text  用户输入文本
     * @param int $uid  用户id
     * @return string
     */
    public function index($text, $uid)
    {
        $data = "{
                reqType:0,
                perception: {
                    inputText: {
                        text: '$text'
                    },      
                },
                userInfo: {
                    apiKey: '$this->apiKey',
                    userId: '$uid',
                }
            }";
        $url = $this->url;
        $tulingRes = $this->http_request($url, $data);
        $json = json_decode($tulingRes);
        $res1 = $json->results;
        $res2 = $res1[0]->values->text;
        return $res2;
    }

    //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
    function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}